package com.markedquilt.comment.coomon;

import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ZhangKe
 * @Description
 * @date 2020/4/18 22:50.
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonRes doError(HttpServletRequest request, HttpServletResponse response,Exception exception){
        CommonError commonError;
        if (exception instanceof BussinessException){
            return CommonRes.create(((BussinessException)exception).getCommonError(),"fail");
        }else if(exception instanceof NoHandlerFoundException){
            commonError=new CommonError(EmBussinessError.NO_HANDLER_FOUND);
            return CommonRes.create(commonError,"fail");
        }else if (exception instanceof ServletRequestBindingException){
            commonError=new CommonError(EmBussinessError.BIND_EXCEPTION_ERROR);
            return CommonRes.create(commonError,"fail");
        }
        else{
            commonError=new CommonError(EmBussinessError.UNKNOW_ERROR);
            System.out.println(exception);
            return CommonRes.create(commonError,"fail");
        }
    }
}
